﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Security;
using System.Collections;
using System.Web.Compilation;
using System.Web.UI;
using System.IO;
using System.Web.Caching;

namespace Amf4Asmx.Web
{
    public static class ServiceUtils
    {
        private static string GetCacheKey(string virtualPath)
        {
            return ("System.Web.Script.Services.WebServiceData:" + virtualPath);
        }

        public static WebServiceData GetWebServiceData(HttpContext context, string virtualPath)
        {
            virtualPath = VirtualPathUtility.ToAbsolute(virtualPath);
            string cacheKey = GetCacheKey(virtualPath);
            WebServiceData applicationService = context.Cache[cacheKey] as WebServiceData;
            if (applicationService == null)
            {
                if (HostingEnvironment.VirtualPathProvider.FileExists(virtualPath))
                {
                    Type compiledType = null;
                    try
                    {
                        compiledType = BuildManager.GetCompiledType(virtualPath);
                        if (compiledType == null)
                        {
                            compiledType = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page)).GetType();
                        }
                    }
                    catch (SecurityException)
                    {
                    }
                    if (compiledType != null)
                    {
                        applicationService = new WebServiceData(compiledType);
                        IEnumerable virtualPaths = BuildManager.GetCachedBuildDependencySet(context, virtualPath).VirtualPaths;
                        if (virtualPaths != null)
                        {
                            List<string> list = new List<string>();
                            foreach (string str2 in virtualPaths)
                            {
                                list.Add(Path.Combine(context.Request.PhysicalApplicationPath, VirtualPathUtility.GetFileName(str2)));
                            }
                            context.Cache.Insert(cacheKey, applicationService, new CacheDependency(list.ToArray()));
                        }
                        else
                        {
                            context.Cache.Insert(cacheKey, applicationService);
                        }
                    }

                }
            }
            return applicationService;
        }
 

    }
}
